package com.director.core.json.impl.gson;

import com.director.core.util.ReflectionUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * @author Simone Ricciardi
 * @version 1.0, 04/07/2012
 */
public class IncludeFieldsTypeAdapter<T> implements JsonSerializer<T> {
   
   private String[] fields;

   public IncludeFieldsTypeAdapter(String[] fields) {
      this.fields = fields;
   }

   @Override
   public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
      try {
         JsonObject srcElement = new JsonObject();
         for(String fieldName : this.fields) {
            Field field = ReflectionUtils.hierarchicalGetDeclaredField(src.getClass(), fieldName);
            field.setAccessible(true);
            Object fieldValue = field.get(src);
            srcElement.add(fieldName, context.serialize(fieldValue));
         }
         return srcElement;
      } catch(Exception e) {
         throw new JsonParseException(e);
      }
   }

}
